#
from werkzeug.exceptions import HTTPException
import json
from flask import jsonify


class Res(object):
    @classmethod
    def ok(cls, **kw):
        kw['status'] = 'success'
        return jsonify(cls.res(**kw))

    @classmethod
    def err(cls, **kw):
        kw['status'] = 'failed'
        return jsonify(cls.res(**kw))

    @classmethod
    def res(cls, **kw):
        rv = {}
        fields = ['status', 'message', 'data']
        for k in kw:
            if k in fields:
                rv[k] = kw[k]
        return rv


class ApiException(HTTPException):
    code = None
    description = None
    status = 'unknown'
    message = None

    def __init__(self, message=None, data=None, description=None, response=None):
        super(HTTPException, self).__init__()
        self.description = None
        self.response = None
        if message:
            self.message = message
        self.data = data

    def get_body(self, environ=None):
        """Get the Json body."""
        rv = {'status': self.status}
        if self.message:
            rv['message'] = self.message
        if self.data:
            rv['data'] = self.data
        rv = json.dumps(rv)
        return rv

    def get_headers(self, environ=None):
        """Get a list of headers."""
        return [("Content-Type", "application/json")]


class ApiOk(ApiException):
    status = 'success'


class ApiErr(ApiException):
    status = 'failed'
    message = 'Server internal error'


class ApiUn(ApiException):
    status = 'unknown'
    message = 'Unknown error'
